package com.tsunami.base;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tsunami.exception.code.ExceptionCode;
import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * @Classname Results
 * @Description 公共返回结果
 * @Date 2020-01-19 17:54
 * @Created by lx
 */
@Data
public class R implements Serializable {
    Integer count; //数据数量
    Integer code; //代码
    String msg;//信息
    Object only;//单数据返回
    private Map<String,Object> extra = new HashMap<>();//返回数据
    /**
     * 构造方法私有化，里面的方法都是静态方法
     * 达到保护属性的作用
     */
    private R(){}
    /**
     * 使用链式编程
     * @return
     */
    public static R ok(){
        R results = new R();
        results.setCode(ExceptionCode.SUCCESS.getCode());
        results.setMsg(ExceptionCode.SUCCESS.getMsg());
        return results;
    }
    public static R error(){
        R results = new R();
        results.setCode(ExceptionCode.FATL.getCode());
        results.setMsg(ExceptionCode.FATL.getMsg());
        return results;
    }
    public R count(Integer count){
        this.setCount(count);
        return this;
    }
    public R code(Integer code){
        this.setCode(code);
        return this;
    }
    public R msg(String msg){
        this.setMsg(msg);
        return this;
    }
    public R exCode(ExceptionCode ec){
        this.setCode(ec.getCode());
        this.setMsg(ec.getMsg());
        return this;
    }
    public R only(Object only){
        this.setOnly(only);
        return this;
    }
    public R data(String key,Object val){
        Map map = new HashMap();
        map.put(key,val);
        this.setExtra(map);
        return this;
    }
    public R data(Object val){
        Map map = new HashMap();
        map.put("data",val);
        this.setExtra(map);
        return this;
    }
    public R data(Map<String,Object> map){
        this.setExtra(map);
        return this;
    }
    public R data(Page page){
        // 获取当前页的数据集
        Object rows = page.getRecords();
        Map<String, Object> map = new HashMap();
        map.put("list",rows);
        // 获取满足条件的总记录数
        Long total = page.getTotal();
//        map.put("pageNum",page.getCurrent());
//        map.put("pageSize",page.getSize());
        this.setCount(Integer.valueOf(total.toString()));
        this.setExtra(map);
        return this;
    }
    /**链式编程结束**/

}
